﻿// Copyright (c) 2009, ids-adi.org /////////////////////////////////////////////
// All rights reserved.
//------------------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the ids-adi.org nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//------------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY ids-adi.org ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL ids-adi.org BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.CodeDom.Compiler;
using System.Text;
using Microsoft.VisualStudio.TextTemplating;
using org.ids_adi.iring.adapter.ruleEngine;
using org.ids_adi.iring.adapter.sparqlEngineeSub;
using org.ids_adi.iring.adapter.semWebEngine;
using org.ids_adi.iring.utility;
using org.ids_adi.qxf;
using org.ids_adi.iring.adapter;
using org.ids_adi.iring.adapter.dtoLayer;
using org.ids_adi.iring.adapter.dtoLayereSub;

namespace org.ids_adi.iring.adaptereSub
{
    public class AdapterServiceProvider
    {
      
        WebCredentials _targetCredentials = null;
        WebProxyCredentials _proxyCredentials = null;

        private Mapping _mapping = null;
        private string _xmlPath = String.Empty;
        private string _mappingPath = String.Empty;
        private string _dtoToQXFPath = String.Empty;
        private string _qxfToRDFPath = String.Empty;
        private string _dataDictionaryPath = String.Empty;
        private string _interfaceServer = String.Empty;
        private string _modelDTOPath = String.Empty;
        private string _idsPath = String.Empty;
        private bool _trimData = false;
        private bool _useSemweb = false;
        private SPARQLEngine _sparqlEngine = null;
        private SemWebEngine _semwebEngine = null;
        private string _tripleStoreConnectionString = String.Empty;

        #region Constants
        private const string MAPPING_FILENAME = "Mapping.xml";
        private const string DTO_TO_QXF_FILENAME = "DTOToQXF.xsl";
        private const string QXF_TO_RDF_FILENAME = "QXFToRDF.xsl";
        private const string DATA_DICTIONARY_FILENAME = "DataDictionary.xml";
        private const string MAPPING_TO_DTO_CLASSES_FILENAME = "MappingToDTOClasses.xsl";
        private const string MAPPING_TO_IDATASERVICE_FILENAME = "MappingToIDataService.xsl";
        #endregion

        /// <summary>
        /// Adapter Service Constructor
        /// </summary>
        public AdapterServiceProvider()
        {
          ConfigSettings configSettings = new ConfigSettings();
          configSettings.BaseDirectoryPath = System.AppDomain.CurrentDomain.BaseDirectory;
          configSettings.XmlPath = System.Configuration.ConfigurationManager.AppSettings["XmlPath"];
          configSettings.TripleStoreConnectionString = System.Configuration.ConfigurationManager.AppSettings["TripleStoreConnectionString"];
          configSettings.ModelDTOPath = System.Configuration.ConfigurationManager.AppSettings["ModelDTOPath"];
          configSettings.IdsPath = System.Configuration.ConfigurationManager.AppSettings["IDataServicePath"];
          configSettings.InterfaceServer = System.Configuration.ConfigurationManager.AppSettings["InterfaceService"];
          configSettings.TrimData = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["TrimData"]);
          configSettings.UseSemweb = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseSemweb"]);
          configSettings.EncryptedToken = System.Configuration.ConfigurationManager.AppSettings["TargetCredentialToken"];
          configSettings.EncryptedProxyToken = System.Configuration.ConfigurationManager.AppSettings["ProxyCredentialToken"];
          configSettings.ProxyHost = System.Configuration.ConfigurationManager.AppSettings["ProxyHost"];
          configSettings.ProxyPort = System.Configuration.ConfigurationManager.AppSettings["ProxyPort"];
          configSettings.TransformPath = System.Configuration.ConfigurationManager.AppSettings["TransformPath"];
          configSettings.DataLayerConfigPath = System.Configuration.ConfigurationManager.AppSettings["DataLayerConfigPath"];
            Directory.SetCurrentDirectory(configSettings.BaseDirectoryPath);
            DTOFactory.configSettings = configSettings;
            _xmlPath = configSettings.XmlPath;
            _mappingPath = _xmlPath + MAPPING_FILENAME;
            _dtoToQXFPath = _xmlPath + DTO_TO_QXF_FILENAME;
            _qxfToRDFPath = _xmlPath + QXF_TO_RDF_FILENAME;
            _dataDictionaryPath = _xmlPath + DATA_DICTIONARY_FILENAME;
            _tripleStoreConnectionString = configSettings.TripleStoreConnectionString;
            _modelDTOPath = configSettings.ModelDTOPath;
            _idsPath = configSettings.IdsPath;
            _interfaceServer = configSettings.InterfaceServer;
            _trimData = configSettings.TrimData;
            _useSemweb = configSettings.UseSemweb;
            string encryptedToken = configSettings.EncryptedToken;
            string encryptedProxyToken = configSettings.EncryptedProxyToken;
            string proxyHost = configSettings.ProxyHost;
            string proxyPortString = configSettings.ProxyPort;

            if (encryptedToken == String.Empty)
            {
                _targetCredentials = new WebCredentials();
            }
            else
            {
                _targetCredentials = new WebCredentials(encryptedToken);
                _targetCredentials.Decrypt();
            }
            
            int proxyPort = 0;
            Int32.TryParse(proxyPortString, out proxyPort);
            if (encryptedProxyToken == String.Empty)
            {
                _proxyCredentials = new WebProxyCredentials();
            }
            else
            {
                _proxyCredentials = new WebProxyCredentials(encryptedProxyToken, proxyHost, proxyPort);
                _proxyCredentials.Decrypt();
            }

            _mapping = GetMapping();

            if (!_useSemweb)
              _sparqlEngine = new SPARQLEngine(_mapping, _interfaceServer, _targetCredentials, _proxyCredentials, _trimData);
            else
              _semwebEngine = new SemWebEngine(_tripleStoreConnectionString, _mapping, _trimData);
        }

        /// <summary>
        /// Gets the mapping by reading Mapping.xml.
        /// </summary>
        /// <returns>Returns mapping object.</returns>
        public Mapping GetMapping()
        {
            try
            {
                if (_mapping == null)
                {
                    _mapping = Utility.Read<Mapping>(_mappingPath, false);
                }

                return _mapping;

            }
            catch (Exception exception)
            {
                throw new Exception("Error while getting Mapping from " + _mappingPath + ". " + exception.ToString(), exception);
            }
        }

     
    }
}